package com.approval.service;

import com.approval.dto.*;
import com.approval.entity.*;
import com.approval.exception.BusinessException;
import com.approval.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限管理服务
 */
@Service
@Transactional
public class PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    /**
     * 创建权限
     */
    public PermissionResponse createPermission(PermissionCreateRequest request) {
        // 验证权限编码是否已存在
        if (permissionMapper.selectByPermissionCode(request.getPermissionCode()) != null) {
            throw new BusinessException("权限编码已存在");
        }
        
        Permission permission = new Permission();
        BeanUtils.copyProperties(request, permission);
        permission.setCreateTime(new Date());
        permission.setUpdateTime(new Date());
        permissionMapper.insert(permission);
        
        return convertToPermissionResponse(permission);
    }
    
    /**
     * 更新权限
     */
    public PermissionResponse updatePermission(Long permissionId, PermissionUpdateRequest request) {
        Permission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }
        
        // 验证权限编码是否已被其他权限使用
        if (!request.getPermissionCode().equals(permission.getPermissionCode()) &&
            permissionMapper.existsByPermissionCodeAndIdNot(request.getPermissionCode(), permissionId)) {
            throw new BusinessException("权限编码已被其他权限使用");
        }
        
        BeanUtils.copyProperties(request, permission, "id", "createTime");
        permission.setUpdateTime(new Date());
        permissionMapper.update(permission);
        
        return convertToPermissionResponse(permission);
    }
    
    /**
     * 删除权限
     */
    public void deletePermission(Long permissionId) {
        Permission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }
        
        // 检查是否有角色使用该权限
        if (rolePermissionMapper.countByPermissionId(permissionId) > 0) {
            throw new BusinessException("该权限下还有角色，不能删除");
        }
        
        // 检查是否有子权限
        List<Permission> children = permissionMapper.selectByParentIdAndStatus(permissionId, null);
        if (!children.isEmpty()) {
            throw new BusinessException("该权限下还有子权限，不能删除");
        }
        
        permissionMapper.deleteById(permissionId);
    }
    
    /**
     * 根据ID获取权限
     */
    public PermissionResponse getPermissionById(Long permissionId) {
        Permission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }
        return convertToPermissionResponse(permission);
    }
    
    /**
     * 分页查询权限
     */
    public PageResponse<PermissionResponse> getPermissions(PageRequestDto pageRequest, String permissionName, 
                                                           String permissionType, String resource, Integer status) {
        int offset = (pageRequest.getPage() - 1) * pageRequest.getSize();
        List<Permission> permissions = permissionMapper.selectWithConditions(permissionName, permissionType, resource, status, offset, pageRequest.getSize());
        long total = permissionMapper.countWithConditions(permissionName, permissionType, resource, status);
        
        List<PermissionResponse> permissionResponses = permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
        
        return new PageResponse<>(permissionResponses, pageRequest.getPage(), pageRequest.getSize(), total);
    }
    
    /**
     * 获取所有权限
     */
    public List<PermissionResponse> getAllPermissions() {
        List<Permission> permissions = permissionMapper.selectAll();
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取权限树
     */
    public List<PermissionResponse> getPermissionTree() {
        List<Permission> allPermissions = permissionMapper.selectByStatus(1);
        
        // 构建权限树
        Map<Long, PermissionResponse> permissionMap = new HashMap<>();
        List<PermissionResponse> rootPermissions = new ArrayList<>();
        
        // 先创建所有权限的响应对象
        for (Permission permission : allPermissions) {
            PermissionResponse response = convertToPermissionResponse(permission);
            permissionMap.put(permission.getId(), response);
        }
        
        // 构建树形结构
        for (Permission permission : allPermissions) {
            PermissionResponse response = permissionMap.get(permission.getId());
            
            if (permission.getParentId() == null) {
                // 根权限
                rootPermissions.add(response);
            } else {
                // 子权限
                PermissionResponse parentResponse = permissionMap.get(permission.getParentId());
                if (parentResponse != null) {
                    if (parentResponse.getChildren() == null) {
                        parentResponse.setChildren(new ArrayList<>());
                    }
                    parentResponse.getChildren().add(response);
                }
            }
        }
        
        // 按排序字段排序
        sortPermissions(rootPermissions);
        
        return rootPermissions;
    }
    
    /**
     * 获取菜单权限
     */
    public List<PermissionResponse> getMenuPermissions() {
        List<Permission> permissions = permissionMapper.selectMenuPermissions();
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取操作权限
     */
    public List<PermissionResponse> getOperationPermissions() {
        List<Permission> permissions = permissionMapper.selectOperationPermissions();
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    /**
     * 根据权限类型获取权限列表
     */
    public List<PermissionResponse> getPermissionsByType(String permissionType) {
        List<Permission> permissions = permissionMapper.selectByPermissionTypeAndStatus(permissionType, 1);
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    /**
     * 根据父权限ID获取子权限列表
     */
    public List<PermissionResponse> getPermissionsByParentId(Long parentId) {
        List<Permission> permissions = permissionMapper.selectByParentIdAndStatus(parentId, 1);
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取根权限列表
     */
    public List<PermissionResponse> getRootPermissions() {
        List<Permission> permissions = permissionMapper.selectRootPermissionsByStatus(1);
        return permissions.stream()
            .map(this::convertToPermissionResponse)
            .collect(Collectors.toList());
    }
    
    // 私有方法
    
    private void sortPermissions(List<PermissionResponse> permissions) {
        if (permissions == null || permissions.isEmpty()) {
            return;
        }
        
        permissions.sort(Comparator.comparing(PermissionResponse::getSortOrder));
        
        for (PermissionResponse permission : permissions) {
            if (permission.getChildren() != null && !permission.getChildren().isEmpty()) {
                sortPermissions(permission.getChildren());
            }
        }
    }
    
    private PermissionResponse convertToPermissionResponse(Permission permission) {
        PermissionResponse response = new PermissionResponse();
        BeanUtils.copyProperties(permission, response);
        
        // 设置父权限名称
        if (permission.getParentId() != null) {
            Permission parentPermission = permissionMapper.selectById(permission.getParentId());
            if (parentPermission != null) {
                response.setParentPermissionName(parentPermission.getPermissionName());
            }
        }
        
        // 设置角色数量
        response.setRoleCount(rolePermissionMapper.countByPermissionId(permission.getId()));
        
        return response;
    }
}